package ro.ciacob.utils {
	import flash.desktop.NativeApplication;

	public class Descriptor {

		public static const DEFAULT_VERSION_DELIMITER:String = '.';
		public static const DEFAULT_VERSION_SEGMENTS_NUMBER:int = 3;

		public static function getAppCopyright():String {
			var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
			var ns:Namespace = descriptor.namespace();
			var appCopy:String = descriptor.ns::copyright;
			return ('© ' + appCopy);
		}

		public static function getAppSignature(withVersion:Boolean = false, withCopyright:Boolean = false):String {
			var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
			var ns:Namespace = descriptor.namespace();
			var appName:String = descriptor.ns::name;
			var ret:String = appName;
			if (withVersion) {
				ret = ret.concat(' ', getAppVersion(false));
			}
			if (withCopyright) {
				ret = ret.concat(' ', getAppCopyright());
			}
			return ret;
		}

		public static function getAppVersion(withBugFixVersion:Boolean = true):String {
			var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
			var ns:Namespace = descriptor.namespace();
			var version:String = descriptor.ns::versionNumber;
			if (!withBugFixVersion) {
				var segments:Array = version.split(DEFAULT_VERSION_DELIMITER);
				if (segments.length >= DEFAULT_VERSION_SEGMENTS_NUMBER) {
					segments.pop();
				}
				version = segments.join('.');
			}
			return version;
		}

		public static function read(descriptorKey:String):String {
			var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
			var ns:Namespace = descriptor.namespace();
			var descriptorValue:String = descriptor.ns::[descriptorKey][0];
			return Strings.trim(descriptorValue);
		}

		/**
		 * Compares two given versions, both in three part notations (i.e.,
		 * '1.5.47').
		 *
		 * Note: Results are unreliable if one of the two uses a different format.
		 *
		 * @param a
		 * 		  First version to compare.
		 *
		 * @param b
		 * 		  Second version to compare.
		 *
		 * @return
		 * 		  Integer 1 if the 'a' version is greater than the 'b' version;
		 * 		  integer -1 if 'a' is less than 'b'; and 0 if they are the same.
		 */
		private function compareThreePartVersions(a:String, b:String):int {
			var aSegments:Array = a.split('.');
			var bSegments:Array = b.split('.');
			var numSegments:Number = Math.min(aSegments.length, bSegments.length);
			for (var i:int = 0; i < numSegments; i++) {
				var aSegment:String = bSegments[i] || '';
				var aVal:int = parseInt(aSegment) as int;
				var bSegment:String = aSegments[i] || '';
				var bVal:int = parseInt(bSegment) as int;
				if (aVal > bVal) {
					return 1;
				}
				if (aVal < bVal) {
					return -1;
				}
			}
			return 0;
		}
	}
}
